<?php

class OfferController extends FBController
{

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}


	public function actionProfilupd() 
	{	
		
		$model = Profil::model()->findbyPK($_POST['val1']);
				$this->renderPartial('_profilupd', array(
				'model'=>$model,
				'profile'=>$this->FBUser_profile, 
				'location'=>$ret_obj,
			), false, true);
	}
	
	public function actionProfil() 
	{
	      	$model = Yii::app()->db->createCommand()
    		->select()
    		->from('{{profil}}')
    		->where('uid="'.$this->FBUser.'"')
    		->queryRow();
    		
    		if(isset($this->FBUser_profile['location']['id'])){
      			try {
				// we do not delete the link, BUT the feed associated with link !!
      			$ret_obj = $this->facebook->api('/'.$this->FBUser_profile['location']['id'],'POST');
      			} catch(FacebookApiException $e) {
					$ret_obj=null;
      			}
    		}
    		
			$this->renderPartial('_profil', array(
				'model'=>$model,
				'profile'=>$this->FBUser_profile, 
				'location'=>$ret_obj,
			), false, true);
	

	}	
	
	
	public function actionA($t=1) {
	
	      	$profil = Yii::app()->db->createCommand()
    		->select()
    		->from('{{profil}}')
    		->where('uid="'.$this->FBUser.'"')
    		->queryRow();
    		
			$criteria=new CDbCriteria(array(
			'condition'=> 'type='.$t.' and distance(lat,lon,'.$profil['lat'].' ,'.$profil['lon'].')*1.609344 <= '.$profil['distance'],
			'order'=>'created DESC',
		));


		$dataProvider=new CActiveDataProvider('Offer', array(
			'pagination'=>array(
				'pageSize'=>5,
			),
			'criteria'=>$criteria,
		));
    		
		$this->render('entry',array(
			'dataProvider'=>$dataProvider,
			'profil' => $profil,
		));
	

	}
public function actionGet() {	
		try {
			$T = $this->facebook->api(
	'/oauth/access_token',' POST',
	                        array( 'client_id'     => 372024222847571,
                                   'client_secret' => 'ecf8b18ac592026bb882cb763108bd57',
                                   'grant_type'    => 'client_credentials',
                                   //authorization_code, client_credentials
                                   'redirect_uri'	   => 'http://fb.audelion.ch/index.php/offer/get',
                       )); 
	print_r($T);
          } catch(FacebookApiException $e) {
        echo $e->getType();
        echo $e->getMessage();
      } 
   
   }
// protected/controllers/SiteController.php
public function actionUpload() {
    $form = new UploadForm;
    if (isset($_POST['UploadForm'])) {
        if ($form->validate()) {
        	$uploaddir = DIRECTORY_SEPARATOR ."tmp". DIRECTORY_SEPARATOR ."a";
        	$dir = dirname(Yii::app()->request->scriptFile) . $uploaddir;
        	
            $form->image = CUploadedFile::getInstance($form, 'image');
            if(!file_exists ($dir )){
            	echo 'dir nicht da!';
            	if(mkdir($dir, 0755)) echo $dir. ' angelegt';
            }
            $file= $dir . DIRECTORY_SEPARATOR . $form->image->name;
            $fbfile = $uploaddir . DIRECTORY_SEPARATOR . $form->image->name;
            echo $file.'<br />';
            echo 'http://fb.audelion.ch'. $fbfile.'<br />';
         $form->image->saveAs($file);
		try {
		$this->facebook->setFileUploadSupport(true);
		//$this->facebook->setAccessToken("AAACEdEose0cBAJxCOfyCc9cASZA4f1BXrPBIavPbbXvi6pmoJZCeq1ZB1OiUh19NezFFwVM802wu7FgtggFcNyZBJePQm2YXormYnwsIGBBlX8T0wk8BTrCBrRrkHwUZD");
		$photo = $this->facebook->api('/me/photos', 'POST',
                        array( 'image' => '@' . $file,
                               'message' => 'Photo '.$form->image->name.' uploaded to OuterSpace!',
                               //'from' => array('id' => $user, 'name' => 'OuterSpace'),
                       ));            
          $this->redirect(array('index'));  
          } catch(FacebookApiException $e) {
        		echo $e->getType();
        		echo $e->getMessage();
      		}  
        }
        echo 'ungültiges Format; erlaubt sind: jpg, gif, jpeg, png';
    } else
    $this->render('upload', array('form'=>$form));
}

	/*************************************************************************************
	 * displays Fotos in Album "OuterSpace" in Facebook
	 */	 
	//************************************************************************************
	public function actionFotoadd($fotolink, $entry)
	{
        
        $state=true;   
      	try{  
      	$fql = "select object_id , link, src_small, caption from photo where object_id = ".$fotolink;
        $ret_obj = $this->facebook->api(array(
                                   'method' => 'fql.query',
                                   'query' => $fql,
                                 ));
      	} catch(FacebookApiException $e) {
      		$err = $e->getMessage();
      		$state=false;
      	}  
		$tmp=Offer::model()->updateByPk($entry,array('photolink'=>$fotolink, 'photo'=>$ret_obj[0]['src_small']));
		//$model->save();
		$this->redirect('/index.php/offer/view/id/'.$entry);
		print_r($ret_obj);
    }

	/*************************************************************************************
	 * displays Fotos in Album "OuterSpace" in Facebook
	 */	 
	//************************************************************************************
	public function actionFotos($entry=0, $start=0 )
	{
      	$state=true;   
      	try{  
      	$fql = "select object_id , link, src_small, caption from photo where aid in (";
		$fql .= ' SELECT aid FROM album WHERE owner='.$this->FBUser.' and name = "OuterSpace Photos")';
      	$fql .= " limit ".$start.",5";
        $ret_obj = $this->facebook->api(array(
                                   'method' => 'fql.query',
                                   'query' => $fql,
                                 ));
      	} catch(FacebookApiException $e) {
      		$err = $e->getMessage();
      		$state=false;
      	}     	
		$this->render('fotos', array(
				'profile'=>$this->FBUser_profile, 
				'loggedin'=> $this->logged_in, 
				'FBReturn' =>$this->FBReturn,
				'status' => $state,
				'error' => $err,
				'ret_obj' => $ret_obj,
				'start' => $start,	
				'entry' => $entry,	
				));
      }
	
	
	
	/*************************************************************************************
	 * Displays a particular model.
	 */
	public function actionDelete($id)
	{
		try {
        	$fql = "select link_id from link where owner = 372024222847571 ";
        	$fql .= "and owner_comment = '".$id."'";

        	$ret_id = $this->facebook->api(array(
                                   'method' => 'fql.query',
                                   'query' => $fql,
                                 ));

      	} catch(FacebookApiException $e) {
      		echo 'FQL: '.$fql.'<br />';
			echo 'link: '.$ret_id[0]['link_id'];
        	echo '<br />'.$e->getType();
        	echo '<br />'.$e->getMessage();
      	}
      	try {
			// we do not delete the link, BUT the feed associated with link !!
      		$ret_obj = $this->facebook->api('/372024222847571_'.$ret_id[0]['link_id'],'DELETE');
      		$this->redirect(array('index'));
      	} catch(FacebookApiException $e) {
			echo 'link: '.$ret_id[0]['link_id'];
        	echo '<br />'.$e->getType();
        	echo '<br />'.$e->getMessage();
      	}

    }

	/*************************************************************************************
	 * adds a Note to OuterSpace
	 */	 
	//************************************************************************************
	public function actionNotedet($id)
	{
      	$state=true;   
      	try{  
      		$fql = "select note_id, title, content, created_time, updated_time from note where uid = ".$this->FBUser;
      		$fql .= ' and note_id = '.$id;
        	$ret_obj = $this->facebook->api(array(
                                   'method' => 'fql.query',
                                   'query' => $fql,
                                 ));
      		$fql = "select link_id from link where owner = 372024222847571 ";
        	$fql .= "and owner_comment = '".$this->FBUser.";".$id."'";
        	$ret_os = $this->facebook->api(array(
                                   'method' => 'fql.query',
                                   'query' => $fql,
                                 ));
      	} catch(FacebookApiException $e) {
      		$state=false;
      	}     	
		$this->render('notedet', array(
				'profile'=>$this->FBUser_profile, 
				'loggedin'=> $this->logged_in, 
				'FBReturn' =>$this->FBReturn,
				'status' => $state,
				'error' => $e,
				'ret_obj' => $ret_obj,
				'ret_os' => $ret_os,
				'facebook' => $this->facebook,		
				));
      }
	/*************************************************************************************
	 * adds a Note to OuterSpace
	 */	 
	//************************************************************************************
	public function actionNote($start=0)
	{
      	$state=true;   
      	try{  
      	$fql = "select note_id, title, content, created_time, updated_time from note where uid = ".$this->FBUser;
      	$fql .= " limit ".$start.",5";
        $ret_obj = $this->facebook->api(array(
                                   'method' => 'fql.query',
                                   'query' => $fql,
                                 ));
      	} catch(FacebookApiException $e) {
      		$err = $e->getMessage();
      		$state=false;
      	}     	
		$this->render('note', array(
				'profile'=>$this->FBUser_profile, 
				'loggedin'=> $this->logged_in, 
				'FBReturn' =>$this->FBReturn,
				'status' => $state,
				'error' => $err,
				'ret_obj' => $ret_obj,
				'start' => $start,		
				));
      }
	/*************************************************************************************
	 * Displays a particular model.
	 */	 
	//************************************************************************************
	public function actionAddnote($id)
	{
	    try {
        $ret_obj = $this->facebook->api('/372024222847571/links', 'POST',
                                    array(
                                      'name' => 'linked to note '.$id,
                                      'link' => "http://www.facebook.com/372024222847571",
                                      'message' => $id,
                                      'description' => $id.' added '.date('Y-m-d H:i:s'),
                                 ));
		$this->redirect(array('own'));

      } catch(FacebookApiException $e) {
		echo 'Note: '.$ret_note.'<br />';
        echo $e->getType();
        echo $e->getMessage();
      }
      }
	/*************************************************************************************
	 * Displays a particular model.
	 */	 
	//************************************************************************************
	public function actionIndex($start=0)
	{
      	$state=true; 
      	$profil = Yii::app()->db->createCommand()
    		->select()
    		->from('{{profil}}')
    		->where('uid="'.$this->FBUser.'"')
    		->queryRow();
    		$sql = 'select o.*, distance (o.lat,o.lon,'.$profil->lat.' ,'.$profil->lon.')*1.609344  from tbl_offer o ';
$sql .= 'where distance (o.lat,o.lon,'.$profil->lat.' ,'.$profil->lon.')*1.609344 <= '.$profil->distance;
$sql .= 'ORDER BY distance ASC';

$connection = Yii::app()->db;
$command = $connection->createCommand($sql);
$results = $command->queryAll();
/*
select o.*, distance (o.lat,o.lon,(SELECT DISTINCT lat from tbl_profil where uid = 100003898944975) ,(SELECT DISTINCT lon from tbl_profil where uid = 100003898944975))*1.609344  from tbl_offer o
where distance (o.lat,o.lon,(SELECT DISTINCT lat from tbl_profil where uid = 100003898944975),(SELECT DISTINCT lon from tbl_profil where uid = 100003898944975))*1.609344 < 750;
    		
      	$model=Yii::app()->db->createCommand()
    		->select()
    		->from('{{offer}} n')
    		->limit(5)
    		->offset($start)
    		->queryall();
    		*/
		$this->render('index', array(
				'profile'=>$this->FBUser_profile, 
				'loggedin'=> $this->logged_in, 
				'profil' => $profil,
				'status' => $state,
				'error' => $err,
				'ret_obj' => $model,
				'start' => $start,	
				));
      }

	/*************************************************************************************
	 * Displays own postings.
	 */
	public function actionOwn()
	{
      	$state=true; 
      	$profil = Yii::app()->db->createCommand()
    		->select('uid,lat, lon')
    		->from('{{profil}}')
    		->where('uid='.$this->FBUser)
    		->queryRow();
    		
		$criteria=new CDbCriteria(array(
			'condition'=> 'uid='.$this->FBUser,
			'order'=>'created DESC',
		));


		$dataProvider=new CActiveDataProvider('Offer', array(
			'pagination'=>array(
				'pageSize'=>5,
			),
			'criteria'=>$criteria,
		));
    		
		$this->render('own', array(
				'profile'=>$this->FBUser_profile, 
				'loggedin'=> $this->FBUser, 
				'FBReturn' =>$this->FBReturn,
				'status' => $state,
				'error' => $err,
				'dataProvider' => $dataProvider,
				'profil' => $profil,
				'start' => $start,	
				));
      }
      
	/**
	 * Displays a particular model.
	 */
	public function actionAlbum()
	{
      try {
       $ret_obj = $this->facebook->api('/me/albums','GET');
        foreach($ret_obj['data'] as $item){
            echo 'id     : '.$item['id'].'<br>';
            echo 'aid    : '.$item['aid'].'<br>';
            echo 'link   : '.$item['link'].'<br>';
            echo 'item: <b>'.$item['name'].'</b> - '.$item['created_time'].'<br />';
            if($item['name'] == "OuterSpace Photos") { $album = $item['id'];        	}
  
		}          
            
       			$ret_photo = $this->facebook->api('/'.$album.'/photos','GET');
        		foreach($ret_photo['data'] as $item){
            echo 'id     : '.$item['id'].'<br>';
            echo 'aid    : '.$item['aid'].'<br>';
            echo 'link   : '.$item['link'].'<br>';
            echo 'item: <b>'.$item['source'].'</b> - '.$item['created_time'].'<br />';
			echo '<img src="'.$item['source'].'" width=64px height=64px /><br />';
        		}

      } catch(FacebookApiException $e) {
		print_r($e);
        echo $e->getType();
        echo $e->getMessage();
      }
      }

	/*************************************************************************************
	 * Displays a particular model.
	 */
	public function actionView($id)
	{
      	$state=true; 
      	
      	$profil = Yii::app()->db->createCommand()
    		->select()
    		->from('{{profil}}')
    		->where('uid='.$this->FBUser)
    		->queryRow();
    		
		$criteria=new CDbCriteria(array(
			'condition'=> 'id='.$id,
			'order'=>'created DESC',
		));


		$dataProvider=new CActiveDataProvider('Offer', array(
			'pagination'=>array(
				'pageSize'=>5,
			),
			'criteria'=>$criteria,
		));
		
      	$model=Offer::model()->findByPk($id);
      	if($model->uid == $this->FBUser) $view = 'owndet';
		else $view = 'view';
		$this->render($view, array(
		    'dataProvider' => $dataProvider,
		    'profil' => $profil,
			'post' => $post,
			'status'=>$state,
			'ret_obj' => $model,
			'user_profile' => $this->FBUser_profile,
		));
	}

	/*************************************************************************************
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
	      	$profil = Yii::app()->db->createCommand()
    		->select()
    		->from('{{profil}}')
    		->where('uid='.$this->FBUser)
    		->queryRow();
    		
		$model = new Offer;
		$model->ownlocation = 0;
		print_r($_POST);
		if(isset($_POST['Offer']))
		{
			if(1==1 ){//$model->validate()){
				$model->attributes=$_POST['Offer'];
				$model->uid = $this->FBUser;
				if($_POST['Offer']['ownlocation'] == 0) {
					$model->lat = $profil['lat'];
					$model->lon = $profil['lon'];
					echo $_POST['Offer']['ownlocation'] ;
				}
				else {

					$coord=get_coordinates($model->location);
					$model->lat = $coord['latitude'];
					$model->lon = $coord['longitude'];
				}
				$model->category = '123456789012345';
				$model->type = $_POST['Offer']['type'];
				echo 'type: '.$model->type;
				$a = $model->save();
				echo 'save: '.$a;
				
				if($_POST['Offer']['notelink']){
			
        $ret_note = $this->facebook->api('/me/links', 'POST',
                                    array(
                                    'link' => "http://apps.facebook.com/myouterspace/",
                                      'message' => $model->content.'\n'.$model->comment.$a,
                                      'subject' => $model->heading,
                                 )); 
			}
			$this->redirect(array('own'));
			}
			Yii::app()->end();
		}

			$this->render('create', array(
				'model'=>$model,
				'status'=>$state,
				'fbprofile' => $this->FBUser_profile,
			));
			
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionTokens()
	{
	    $fb_key = 'fbs_372024222847571';
		$cookie = Yii::app()->request->cookies[$fb_key]->value;
		$datr = Yii::app()->request->cookies['datr']->value;
		echo 'user               : '.$this->FBUser.'<br />';
		echo 'profile            : '.$this->FBUser_profile['name'].'<br />';
		echo 'request oauth_token: '.$this->FBRequest['oauth_token'].'<br />';
		echo 'init oauth_token   : '.$this->FBoauth.'<br />';
		echo 'facebook token     : '.$this->facebook->getAccessToken().'<br />';
		echo 'facebook link      : '.$this->FBReturn.'<br />';
		echo 'cookie             : '.$cookie.'<br />';
		echo 'cookie datr        : '.$datr.'<br />';
		echo '<pre>';
		print_r($this->FBRequest);
		echo '</pre>';
		$ret_obj = $this->facebook->api('/me/permissions', 'GET');
		echo 'Permissions: <br /><pre>';
		print_r($ret_obj);
		echo '</pre>';	
	}
	
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
			{
				if(Yii::app()->user->isGuest)
					$condition='status='.Post::STATUS_PUBLISHED.' OR status='.Post::STATUS_ARCHIVED;
				else
					$condition='';
				$this->_model=Post::model()->findByPk($_GET['id'], $condition);
			}
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Creates a new comment.
	 * This method attempts to create a new comment based on the user input.
	 * If the comment is successfully created, the browser will be redirected
	 * to show the created comment.
	 * @param Post the post that the new comment belongs to
	 * @return Comment the comment instance
	 */
	protected function newComment($post)
	{
		$comment=new Comment;
		if(isset($_POST['ajax']) && $_POST['ajax']==='comment-form')
		{
			echo CActiveForm::validate($comment);
			Yii::app()->end();
		}
		if(isset($_POST['Comment']))
		{
			$comment->attributes=$_POST['Comment'];
			if($post->addComment($comment))
			{
				if($comment->status==Comment::STATUS_PENDING)
					Yii::app()->user->setFlash('commentSubmitted','Thank you for your comment. Your comment will be posted once it is approved.');
				$this->refresh();
			}
		}
		return $comment;
	}
}
